<?php
namespace App\Services;

use App\Models\Article;
use App\Models\UserRead;
use App\Models\UserReadLog;
use function EasyWeChat\Kernel\Support\get_client_ip;

class ReadStoreService
{
    public static function handle($user_id, $article_ids, $fake_user_id, $is_migrate = false) {
        if (!$user_id) {
            $ip = get_client_ip();
            \Log::error($ip . ' user_id not exists');
            return ;
        }

        $arr_article_id = explode(",", $article_ids);
        $model = UserRead::where('uid', $user_id)->first();
        if (!$model) {
            $model = new UserRead();
            $content = '';
        } else {
            $content = $model->content;
        }
        Article::whereIn('id', $arr_article_id)->increment('pv', 1);
        $log = new UserReadLog(['user_id' => $user_id]);
        if ($is_migrate)
            $fake_log = new UserReadLog(['user_id' => $fake_user_id]);

        $arr = [];
        foreach ($arr_article_id as $key => $id) {
            if (strpos($content, "," . $id . ",") !== false) {
                unset($arr_article_id[$key]);
            }
            if ($is_migrate) {
                $created_at = $fake_log->where('user_id', $fake_user_id)->where('article_id', $id)->value('created_at');
                if (!$created_at)
                    $created_at = date('Y-m-d H:i:s');

                array_push($arr, [
                    'user_id' => $user_id,
                    'article_id' => $id,
                    'created_at' => $created_at
                ]);
            } else {
                array_push($arr, [
                    'user_id' => $user_id,
                    'article_id' => $id
                ]);
            }
        }
        if (!empty($arr))
            $log->insert($arr);

        $arr_article_id = array_filter($arr_article_id);
        if (!empty($arr_article_id) && $user_id) {
            if ($content)
                $content .=  implode(",", $arr_article_id) . ",";
            else
                $content .= "," . implode(",", $arr_article_id) . ",";

            $model->content = $content;
            $model->uid = $user_id;
            $model->save();
        }



    }

}